package com.zeng.user.utils;

import java.util.*;

/**
 * @author zyb
 * @date 2021-05-17 21:16
 */
public class ConsistentHash {
    /**
     * 待添加入Hash环的服务器列表
     */
    public static final Set<String> SERVERS = new HashSet<>(Arrays.asList("192.168.0.0:111", "192.168.0.1:111",
            "192.168.0.2:111", "192.168.0.3:111", "192.168.0.4:111"));

    private final SortedMap<Integer, String> cachedMap = new TreeMap<>();


    public ConsistentHash(Set<String> servers) {
        for (String server : servers) {
            addServer(server);
        }
    }

    public void addServer(String server) {
        int hash = hashCode(server);
        cachedMap.put(hash, server);
    }

    public void removeServer(String server) {
        int hash = hashCode(server);
        cachedMap.remove(hash);
    }


    public String getServer(String key) {
        int hash = hashCode(key);
        SortedMap<Integer, String> tailMap = cachedMap.tailMap(hash);
        if (tailMap.isEmpty()) {
            tailMap = cachedMap;
        }
        return cachedMap.get(tailMap.firstKey());
    }

    private static int hashCode(String source) {
        return Math.abs(source.hashCode());

    }

    public static void main(String[] args) {
        ConsistentHash consistentHash = new ConsistentHash(SERVERS);
        String server = consistentHash.getServer("test");
        System.out.println(server);
    }

}
